package org.robot.scm.platform.server.handler.archery;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpCookie;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.server.handler.BaseHandler;
import org.robot.scm.utils.JsonHelper;

@Slf4j
@NoArgsConstructor
public class ArcheryAuditHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/archery/audit";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String requestBody = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n"));
        Map<String, String> queryMap = JsonHelper.toMap(requestBody);
        Integer workflowId = Integer.valueOf(queryMap.get("workflow_id"));
        String result = audit(workflowId);
        sendSuccessResponse(exchange, "审核成功", result);
    }

    public static String extractTokenByHtml(String html) {
        // 正则表达式匹配csrfmiddlewaretoken的value
        String regex = "name=\"csrfmiddlewaretoken\"\\s+value=\"([^\"]+)\"";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(html);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return StringUtils.EMPTY;
    }

    private String audit(Integer workflowId) {
        String token = RedisCacheHelper.get("archery_token");
        String sessionId = RedisCacheHelper.get("archery_session");
        HttpResponse detailPage = HttpUtil.createRequest(Method.GET, ArcheryConfig.ARCHERY_URL + "/detail/" + workflowId + "/")
                .cookie(new HttpCookie("csrftoken", token), new HttpCookie("sessionid", sessionId))
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "max-age=0")
                .header("Connection", "keep-alive")
                .header("Upgrade-Insecure-Requests", "1")
                .header("Referer", ArcheryConfig.ARCHERY_URL + "/sqlworkflow/")
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36")
                .execute();
        String location = detailPage.header("Location");
        if (StringUtils.contains(location, "login")) {
            ArcheryHelper.loginAndSession();
            return audit(workflowId);
        }
        String detailBody = detailPage.body();
        String csrfMiddlewareToken = extractTokenByHtml(detailBody);

        String auditUrl = ArcheryConfig.ARCHERY_URL + "/passed/";
        HttpResponse response = HttpUtil.createRequest(Method.POST, auditUrl)
                .cookie(new HttpCookie("csrftoken", token), new HttpCookie("sessionid", sessionId))
                .body("csrfmiddlewaretoken=" + csrfMiddlewareToken + "&workflow_id=" + workflowId + "&audit_remark=1")
                .execute();
        return response.body();
    }
}
